<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\FinanceWealthStream;
use App\Model\FlockModel;
use App\Model\OperationLogs;
use App\Model\Prop;
use App\Model\Room;
use App\Model\Union;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


//公会相关
class UnionController extends BaseController
{
    protected $model;
    protected $modelFlock;
    protected $modelProp;
    public function __construct(Request $request, Union $union, FlockModel $flockModel, Prop $prop)
    {
        parent::__construct($request);
        $this->model = $union;
        $this->modelFlock = $flockModel;
        $this->modelProp = $prop;
    }

    //公会列表
    public function index(Request $request)
    {
        $baseResult = $this->model->getList($request->input());
        $paramResult = $this->model->getUnionParam();
        $unionParam = [];
        if ($paramResult) {
            $unionParam = array_column($paramResult, null, 'union_id');
        }
        foreach ($baseResult['data'] as $key => $val) {
            if (isset($unionParam[$val['id']])) {
                $baseResult['data'][$key]['set_param'] = 1;
            } else {
                $baseResult['data'][$key]['set_param'] = 0;
            }

            //获取财富等级与活跃等级
            $rankInfo = $this->model->getGrade($val['id']);
            $baseResult['data'][$key]['rankVal'] = $rankInfo['rankVal'];
            $baseResult['data'][$key]['rankActiveVal'] = $rankInfo['rankActiveVal'];
        }
        return $this->toJson(self::SUCCESS, $baseResult);
    }

    public function createUnion(Request $request)
    {
        $input = $request->input();
        $user_id = $input['user_id'];
        $un_info = $this->model->getUserUnionInfo($user_id);
        if ($un_info) {
            return $this->toJson(self::ERROR, [], '该用户已有工会');
        }
        $api = json_decode(curlRequest(getKkaudioApiUrl() . '/inner/union/createUnion', $input), true);
        if ($api['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::UNION, 'createUnion');
            $this->buildTrieTree();
            return $this->toJson(self::SUCCESS, $api);
        }
        return $this->toJson(self::ERROR, [], '失败');
    }

    public function setUnionInfo(Request $request)
    {
        $input = $request->input();
        if (empty($input['portrait'])) unset($input['portrait']);
        if (empty($input['name'])) unset($input['name']);
        if (empty($input['notice'])) unset($input['notice']);
        if (empty($input['desc'])) unset($input['desc']);
        if (empty($input['sort'])) unset($input['sort']);
        if (empty($input['reward_type'])) unset($input['reward_type']);//公会奖励类型 单独接口
        $api = json_decode(curlRequest(getKkaudioApiUrl() . '/inner/union/updateUnion', $input), true);
        if ($api['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::UNION, 'setUnionInfo');
            $this->buildTrieTree();
            return $this->toJson(self::SUCCESS, $api);
        }
        return $this->toJson(self::ERROR, [], '失败');
    }

    //设置公会奖励类型
    public function unionSetRewardType(Request $request){
        $res = $this->model->unionSetRewardType($request->all());
        if($res['code'] == self::SUCCESS) {
            OperationLogs::createData($request, OperationLogs::UNION, '设置公会奖励类型');
        }
        return $this->toJson($res['code'], $res['data'], $res['msg']);
    }


    //获取公会房间
    public function getUnionRoom(Request $request)
    {
        $union_id = $request->input('id', 0);
        $res = $this->model->getUnionRooms($union_id);
        return $this->toJson(self::SUCCESS, $res);
    }

    //房间编入公会
    public function roomJoinUnion(Request $request, Room $room)
    {
        $input['union_id'] = $request->input('id');
        $input['room_id'] = $request->input('room_id');
        if (!$input['union_id'] || !$input['room_id']) {
            return $this->toJson(self::ERROR, [], '失败');
        }
        $room_info = objToArray($room->getRoomByRoomid($input['room_id']));
        if ($room_info['business_type'] == 0) {
            return $this->toJson(self::ERROR, [], '小屋不可编入工会');
        }
        $api = json_decode(curlRequest(getKkaudioApiUrl() . '/inner/union/roomJoinUnion', $input), true);
        if ($api['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::UNION, '房间编入公会');
            return $this->toJson(self::SUCCESS, $api);
        }
        return $this->toJson(self::ERROR, [], '失败');
    }

    //公会用户
    public function userList(Request $request)
    {
        $res = $this->model->getUnionUser($request->input());
        return $this->toJson(self::SUCCESS, $res);
    }

    //解散公会
    public function delUnion(Request $request)
    {
        $data['user_id'] = $request->input('un_user_id');
        $api = json_decode(curlRequest(getKkaudioApiUrl() . '/inner/union/cmsDissolveUnion', $data), true);
        if ($api['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::UNION, '解散公会');
            $this->buildTrieTree();
            return $this->toJson(self::SUCCESS, $api);
        }
        return $this->toJson(self::ERROR, [], '失败');
    }

    public function createGroup(Request $request)
    {
        $user_id = $request->input('un_user_id');
        //查看工会信息
        $union_info = $this->model->getUnionInfo($user_id);
        if (!$union_info) {
            return $this->toJson(self::ERROR, [], '失败');
        }
        $data['user_id'] = $union_info['un_user_id'];
        $data['group_chat_name'] = $union_info['name'];
        $data['group_chat_image'] = $union_info['portrait'];
        $data['notice_content'] = $union_info['notice'];
        $data['desc'] = $union_info['desc'];
        $data['liang'] = 0;
        $res = $this->modelFlock->createData($data);
        if ($res['code'] === 0) {
            OperationLogs::createData($request, OperationLogs::UNION, 'createGroup');
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }


    public function getUnionSign(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->getSigning($request->input()));
    }

    public function reliveUser(Request $request)
    {
        $data['user_id'] = $request->input('user_id', 0);
        $api = curl_request(getKkaudioApiUrl() . '/inner/union/cmsReliveUser', $data, 'urlencoded', 'GET');
        if ($api['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::UNION, '解约用户');
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], '失败');

    }

    public function kickUser(Request $request)
    {
        $data['user_id'] = $request->input('user_id', 0);
        $data['union_id'] = $request->input('un_id', 0);
        $role_id = $request->input('role_id', 0);
        if ($role_id == 1) {
            return $this->toJson(self::ERROR, [], '会长不可踢出公会');
        }
        $api = curl_request(getKkaudioApiUrl() . '/inner/union/cmsKickUnionUser', $data, 'urlencoded', 'GET');
        if ($api['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::UNION, '踢出公会');
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], '失败');

    }


    public function createUnionParam(Request $request)
    {
        $input['union_id'] = $request->input('union_id');
        $input['m_daily_advance'] = $request->input('m_daily_advance');
        $input['m_self_advance'] = $request->input('m_self_advance');
        $input['m_set_advance'] = $request->input('m_set_advance');
        $input['m_daily_withdraw'] = $request->input('m_daily_withdraw');
        $input['m_set_withdraw'] = $request->input('m_set_withdraw');

        if (empty($input['m_daily_advance']) && empty($input['m_self_advance']) && empty($input['m_set_advance']) && empty($input['m_daily_withdraw']) && empty($input['m_set_withdraw'])) {
            return $this->toJson(self::ERROR, [], '未变更公会权限');
        }

        if (empty($input['union_id'])) {
            return $this->toJson(self::ERROR, [], '公会ID为空');
        }

        $res = $this->model->createUnionParam($input);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '创建公会权限');
        return $this->toJson(self::SUCCESS);
    }


    public function getUnionParamList(Request $request)
    {
        $unionId = $request->input('union_id');
        if (empty($unionId)) {
            return $this->toJson(self::ERROR, [], '公会ID为空');
        }

        $result = $this->model->getUnionParamList($unionId);
        if (empty($result)) {
            return $this->toJson(self::ERROR, [], '暂无相关公会权限信息');
        }
        return $this->toJson(self::SUCCESS, $result);
    }


    public function updateUnionParam(Request $request)
    {
        $unionId = $request->input('union_id');
        $dailyAdvance = $request->input('m_daily_advance');
        $selfAdvance = $request->input('m_self_advance');
        $setAdvance = $request->input('m_set_advance');
        $dailyWithdraw = $request->input('m_daily_withdraw');
        $setWithdraw = $request->input('m_set_withdraw');

        if (empty($unionId)) {
            return $this->toJson(self::ERROR, [], '公会ID为空');
        }
        $result = $this->model->getUnionParamList($unionId);
        if (empty($result)) {
            return $this->toJson(self::ERROR, [], '暂无相关公会权限信息');
        }
        $input = [];
        if ($dailyAdvance != $result['m_daily_advance']) {
            $input['m_daily_advance'] = $dailyAdvance;
        }
        if ($selfAdvance != $result['m_self_advance']) {
            $input['m_self_advance'] = $selfAdvance;
        }
        if ($setAdvance != $result['m_set_advance']) {
            $input['m_set_advance'] = $setAdvance;
        }
        if ($dailyWithdraw != $result['m_daily_withdraw']) {
            $input['m_daily_withdraw'] = $dailyWithdraw;
        }
        if ($setWithdraw != $result['m_set_withdraw']) {
            $input['m_set_withdraw'] = $setWithdraw;
        }

        if (empty($input)) {
            return $this->toJson(self::SUCCESS);
        }
        $input['union_id'] = $unionId;

        $updateResult = $this->model->updateUnionParam($input);

        if ($updateResult['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $updateResult['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '修改公会权限');
        return $this->toJson(self::SUCCESS);
    }

    public function getUnionMallList(Request $request)
    {
        $startTime = $request->input('begin_date');
        $endTime = $request->input('end_date');

        if (strtotime($startTime) > strtotime($endTime)) {
            return $this->toJson(self::ERROR, [], '查询时间范围有误');
        }

        $result = $this->model->getUnionMallList($request->input());
        $result = json_decode(json_encode($result), true);

        if ($result['data']) {
            $propIds = array_unique(array_column($result['data'], 'prop_id'));
            $propInfo = $this->modelProp->getPropInfoByIds($propIds);
            $propName = array_column($propInfo, 'name', 'prop_id');
            foreach ($result['data'] as $key=>$val) {
                $result['data'][$key]['mallName'] = '';
                if (isset($propName[$val['prop_id']])) {
                    $result['data'][$key]['mallName'] = $propName[$val['prop_id']];
                }
                $result['data'][$key]['up_time'] = date('Y-m-d', $val['up_time']);
            }
        }

        return $this->toJson(self::SUCCESS, $result);
    }

    public function deletePropItem(Request $request, $id)
    {
        $res = $this->model->deletePropItem(['id' => $id]);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '删除公会商城记录', $id);
        return $this->toJson(self::SUCCESS);
    }

    public function getProps(Request $request)
    {
        $result = $this->modelProp->getProps($request);

        return $this->toJson(self::SUCCESS, $result);
    }

    public function createUnionShopItem(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'prop_id' => 'required',
            'status' => 'required',
            'active_level' => 'required',
            'value' => 'required',
            'num' => 'required'
        ], [
            'prop_id.required' => '道具Id不可为空',
            'status.required' => '显示状态不可为空',
            'active_level.required' => '解锁等级不可为空',
            'value.required' => '所需贡献值不可为空',
            'num.required' => '商品数量不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $input['desc'] = $request->input('desc') ?? '';
        $input['prop_id'] = $request->input('prop_id');
        $input['value'] = intval($request->input('value'));
        $input['num'] = intval($request->input('num'));
        $input['active_level'] = $request->input('active_level');
        $input['status'] = $request->input('status');
        $input['up_time'] = $request->input('up_time') ? strtotime($request->input('up_time')) : time();

        $res = $this->model->createUnionShopItem($input);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '新增公会商城道具');
        return $this->toJson(self::SUCCESS);
    }


    public function updateUnionShopItem(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'prop_id' => 'required',
            'status' => 'required',
            'active_level' => 'required',
            'value' => 'required',
            'num' => 'required'
        ], [
            'id.required' => '列表Id不可为空',
            'prop_id.required' => '道具Id不可为空',
            'status.required' => '显示状态不可为空',
            'active_level.required' => '解锁等级不可为空',
            'value.required' => '所需贡献值不可为空',
            'num.required' => '商品数量不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $input['id'] = $request->input('id');
        $input['desc'] = $request->input('desc') ?? '';
        $input['prop_id'] = $request->input('prop_id');
        $input['value'] = intval($request->input('value'));
        $input['num'] = intval($request->input('num'));
        $input['active_level'] = $request->input('active_level');
        $input['status'] = $request->input('status');
        $input['up_time'] = $request->input('up_time') ? strtotime($request->input('up_time')) : time();

        $res = $this->model->updateUnionShopItem($input);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '修改公会商城道具', $input['id']);
        return $this->toJson(self::SUCCESS);
    }
    public function getRoomWater(Request $request,FinanceWealthStream $financeWealthStream,$union_id){
        $roomArr = $this->model->getUnionRooms($union_id);
        $room_idStr = implode(',',array_column($roomArr,'room_id'));
        return $this->toJson(self::SUCCESS, $financeWealthStream->getUnionRoomWealthWater($request, $room_idStr));
    }


    public function union_send_goods(Request $request)
    {
        $params = $request ->all();

        $url = getKkaudioApiUrl();
        $res = curl_request($url.'/inner/mall/union_send_goods', $params, 'json','POST');
        write_log('UnionSendGoods','sendGoods store response' , ['params'=>$params, 'res'=>$res]);
        if ($res && $res['code']==0){
            AdminLog::createData($request, AdminLog::SEND_GOODS_RECORD, "赠送工会商品");
            return $this->toJson(self::SUCCESS, '', $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '赠送工会商品');

        return $this->toJson(self::PARAM_ERROR, '', $res['msg']??'异常');
    }

    /**
     * 构建trie树
     * @return bool
     */
    public function buildTrieTree(): bool
    {
        //暂停使用此种方式
        //return $this->model->createTrieTree();
        return true;
    }
}
